#include "StdAfx.h"

#include "yasli/STL.h"
#include "yasli/Archive.h"
#include "yasli/STLImpl.h"

#include "yasli/TextIArchive.h"
#include "yasli/TextOArchive.h"

#include "Preferences.h"
#include "utils/Macros.h"
#include "utils/Files.h"

PreferencesBlock::PreferencesBlock(const char* name, bool editable)
: name_(name)
, editable_(editable)
{
	PreferencesMaster::the().registerBlock(this);
}

// ---------------------------------------------------------------------------

PreferencesMaster::PreferencesMaster()
{
}

void PreferencesMaster::registerBlock(PreferencesBlock* block)
{
	blocks_.push_back(block);
}

PreferencesMaster& PreferencesMaster::the()
{
	static PreferencesMaster preferencesMaster;
	return preferencesMaster;
}

void PreferencesMaster::serialize(Archive& ar)
{
	Blocks::iterator it;
	FOR_EACH(blocks_, it){
		PreferencesBlock* block = *it;
		if(!ar.isEdit() || block->editable())
			ar(*block, block->name());
	}
}

void PreferencesMaster::setFileName(const char* fileName)
{
	if(Files::exists(fileName) && fileName_.empty()){
		TextIArchive ia;
		ia.open(fileName);
		serialize(ia);
	}
	fileName_ = fileName;
}

void PreferencesMaster::save()
{
	if(fileName_.empty())
		return;

	Files::createDirectoryForFile(fileName_.c_str());
	TextOArchive oa;
	oa.open(fileName_.c_str());
	serialize(oa);
}